package common

import "net/http"

// 声明一个新的数据类型(函数类型)
type FilterHandler func(w http.ResponseWriter,r *http.Request) error

// 拦截器结构体
type Filter struct {
	// 用来存储需要拦截的URI
	filterMap map[string]FilterHandler
}

// Filter 初始化函数
func NewFilter() *Filter {
	return &Filter{
		filterMap: make(map[string]FilterHandler),
	}
}
// 注册拦截器
func (f *Filter) RegisterFilterUri(uri string, handler FilterHandler) {
	f.filterMap[uri] = handler
}

// 根据uri获取对应的handler
func (f *Filter) GetFilterHandler(uri string) FilterHandler {
	return f.filterMap[uri]
}

func (f *Filter) Handler(handler WebHandler) func(w http.ResponseWriter, r *http.Request) {
	return func(w http.ResponseWriter, r *http.Request) {
		for _, filterHandler := range f.filterMap {
			// 执行拦截业务逻辑
			err := filterHandler(w, r)
			if err != nil {
				w.Write([]byte(err.Error()))
				return
			}
			// 跳出循环
			break
		}
		// 执行正常注册的逻辑
		handler(w,r)
	}
}

// 声明函数类型
type WebHandler func(w http.ResponseWriter,r *http.Request)


